//
//  HomeViewController.m
//  KiklinkApp
//
//  Created by LJC on 14-9-2.
//  Copyright (c) 2014年 Kiklink. All rights reserved.
//

#import "HomeViewController.h"

#import "ImagesManager.h"
#import "UIColor+hex.h"
#import "UIView+loadWithNib.h"

#import "SearchBar.h"
#import "HomeUpView.h"
#import "HomeCell.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"

#import "API.h"

#import "SearchViewController.h"
#import "ProductViewController.h"

static NSString *HomeTableCellIdentifiers = @"HomeCell";

@interface HomeViewController ()
{
    //data
    NSMutableArray *bannerImages;
    NSMutableArray *recommendations;
    NSInteger page;
    NSInteger totalPage;
    
    //ui
    UIBarButtonItem *searchItem;
    SearchBar *search;
    UIBarButtonItem *searchBarItem;
    UIImageView *logoView;
}
@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"首页";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    
    //loading
    [self.activity startAnimating];
    self.refreshBtn.hidden = YES;
    self.placeHoldView.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.placeHoldView.hidden = NO;
    [self.refreshBtn addTarget:self action:@selector(refresh) forControlEvents:UIControlEventTouchUpInside];
    
    
    //BundleImages
    ImagesManager *imagesManager = [ImagesManager sharedImagesManager];
    
    
    //leftNavItem
    logoView = [[UIImageView alloc] initWithImage:[imagesManager logo]];
    [logoView setFrame:CGRectMake(0, 0, NavBarHeight*60/44, NavBarHeight*24/44)];
    UIBarButtonItem *leftNavBarItem = [[UIBarButtonItem alloc] initWithCustomView:logoView];
    self.navigationItem.leftBarButtonItem = leftNavBarItem;
    
    
    //rightNavItem
    searchItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchBarPresent)];
    searchItem.tintColor = [UIColor colorWithHexString:AppColor_Main andAlpha:0.8];
    
    search = [[SearchBar alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth*9/10, NavBarHeight)];
    search.placeholder = @"向右滑动取消";
    search.delegate = self;
    UISwipeGestureRecognizer *rightSwip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(searchBarDismis)];
    rightSwip.direction = UISwipeGestureRecognizerDirectionRight;
    [search addGestureRecognizer:rightSwip];
    searchBarItem = [[UIBarButtonItem alloc] initWithCustomView:search];
    
    self.navigationItem.rightBarButtonItem = searchItem;

    
    //backScrollView
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.backScrollView.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.backScrollView.delegate = self;
    self.backScrollView.dataSource = self;
    self.backScrollView.showsVerticalScrollIndicator = NO;
    [self.backScrollView registerClass:[UITableViewCell class] forCellReuseIdentifier:HomeTableCellIdentifiers];
    [self setupRefresh];
    [self.backScrollView reloadData];

    
    //data
    recommendations = [[NSMutableArray alloc] init];
    page = 1;
    [self getData:1 Condition:@"first"];
    
    bannerImages = [[NSMutableArray alloc] init];
    [self getBanners];
}

#pragma get data
- (void)getBanners
{
    [API homeActivityImageWithCallback:^(int stateCode, NSString *word, id content) {
        
        if (stateCode == SUCCESS) {
            
            NSMutableArray *result = (NSMutableArray *)content;
            NSMutableArray *temp = [[NSMutableArray alloc] init];
            for (HomeImage *homeImage in result) {
                [temp addObject:homeImage.content.img];
            }
            bannerImages = temp;
            [self.backScrollView reloadData];

        }
    }];
}

//condition:first&header&footer
- (void)getData:(NSInteger)pageNum Condition:(NSString *)condition
{
    NSLog(@"page:%ld",(long)pageNum);
    [API homeRecommendPageWithPageNumber:[NSNumber numberWithInteger:pageNum] Callback:^(int stateCode, NSString *word, id content) {
        
        if (stateCode == SUCCESS) {
            ProductPage *productPage = (ProductPage *)content;
            NSMutableArray *result = [[NSMutableArray alloc] initWithArray:productPage.result];
            
            if ([condition isEqualToString:@"first"]) {
                totalPage = productPage.lastPageNumber;
                self.backScrollView.scrollEnabled = YES;
                page = 2;
                recommendations = result;
            } else if ([condition isEqualToString:@"header"]) {
                page = 2;
                recommendations = result;
            } else if ([condition isEqualToString:@"footer"]) {
                page ++;
                [recommendations addObjectsFromArray:result];
            }
            
            [self loadData:condition];
            
        } else {
            if ([condition isEqualToString:@"first"]) {
                self.backScrollView.scrollEnabled = NO;
                [self.activity stopAnimating];
                self.refreshBtn.hidden = NO;
            } else if ([condition isEqualToString:@"header"]) {
                [self.backScrollView headerEndRefreshing];
            } else if ([condition isEqualToString:@"footer"]) {
                [self.backScrollView footerEndRefreshing];
            }
        }
        
    }];
    
}

- (void)loadData:(NSString *)condition
{
    [self.backScrollView reloadData];
    
    if ([condition isEqualToString:@"first"]) {
        self.placeHoldView.hidden = YES;
        [self.activity stopAnimating];
    } else if ([condition isEqualToString:@"header"]) {
        [self.backScrollView headerEndRefreshing];
    } else if ([condition isEqualToString:@"footer"]) {
        [self.backScrollView footerEndRefreshing];
    }
}

- (void)refresh
{
    self.refreshBtn.hidden = YES;
    [self.activity startAnimating];
    
    [self getData:1 Condition:@"first"];
    [self getBanners];
}
#pragma get data End

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    
    self.title = @"首页";
    [logoView setHidden:NO];
    [search resignFirstResponder];
    self.navigationItem.rightBarButtonItem = searchItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - searchBarPresent&dismiss&input
- (void)searchBarPresent
{
    CATransition *animation = [CATransition animation];
    animation.duration = 0.0;
    animation.type = @"push";
    animation.subtype = @"fromRight";
    
    self.title = @"";
    [logoView setHidden:YES];
    self.navigationItem.rightBarButtonItem = searchBarItem;
    
    [self.navigationController.navigationBar.layer addAnimation:animation forKey:nil];
    [search becomeFirstResponder];
}
- (void)searchBarDismis
{
    CATransition *animation = [CATransition animation];
    animation.duration = 0.4;
    animation.type = @"push";
    animation.subtype = @"fromLeft";
    
    self.title = @"首页";
    [logoView setHidden:NO];
    [search resignFirstResponder];
    self.navigationItem.rightBarButtonItem = searchItem;
    
    [self.navigationController.navigationBar.layer addAnimation:animation forKey:nil];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    searchVC.keyWord = searchBar.text;
    [self.navigationController pushViewController:searchVC animated:YES];
}
#pragma mark - searchBarPresent&dismiss&input End

#pragma tableView dataSource&delegate &MJRefresh
- (void)setupRefresh
{
    [self.backScrollView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.backScrollView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    self.backScrollView.headerPullToRefreshText = @"下拉可以刷新";
    self.backScrollView.headerReleaseToRefreshText = @"松开马上刷新";
    self.backScrollView.headerRefreshingText = @"正在刷新...";
    self.backScrollView.footerPullToRefreshText = @"上拉加载更多";
    self.backScrollView.footerReleaseToRefreshText = @"松开马上加载";
    self.backScrollView.footerRefreshingText = @"正在加载...";
}
- (void)headerRereshing
{
    //data
    [self getData:1 Condition:@"header"];
    [self getBanners];
}
- (void)footerRereshing
{
    //data
    if (page <= totalPage) {
        [self getData:page Condition:@"footer"];
    } else {
        [self.backScrollView footerEndRefreshing];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return recommendations.count+1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        self.homeUpView = [HomeUpView loadWithNib:@"HomeUpView" AndPostion:CGPointZero];
        
        self.homeUpView.scrollView.pagingEnabled = YES;
        self.homeUpView.scrollView.showsHorizontalScrollIndicator = NO;
        self.homeUpView.scrollView.delegate = self;
        
        if (bannerImages.count != 0) {
            self.homeUpView.scrollView.contentSize = CGSizeMake(ScreenWidth*bannerImages.count, 0);
            for (int i = 0; i < bannerImages.count; i ++) {
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i*ScreenWidth, 0, ScreenWidth, 110)];
                imageView.contentMode = UIViewContentModeScaleAspectFill;
                [imageView sd_setImageWithURL:[NSURL URLWithString:[Base_Url stringByAppendingString:[bannerImages objectAtIndex:i]]] placeholderImage:[UIImage imageNamed:@"placeHolder.png"]];
                [self.homeUpView.scrollView addSubview:imageView];
            }
            self.homeUpView.pageControl.numberOfPages = bannerImages.count;
        }
        
        self.homeUpView.pageControl.currentPage = 0;
        self.homeUpView.pageControl.pageIndicatorTintColor = [UIColor colorWithHexString:AppColor_Unselected andAlpha:0.3];
        self.homeUpView.pageControl.currentPageIndicatorTintColor = [UIColor colorWithHexString:AppColor_PageControl];
        [self.homeUpView.pageControl addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bigWhiteLabelTapped)];
        [self.homeUpView.localView addGestureRecognizer:tap];
        
        return self.homeUpView;
    } else {
        BOOL nibsRegistered = NO;
        if (!nibsRegistered) {
            UINib *nib = [UINib nibWithNibName:@"HomeCell" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:HomeTableCellIdentifiers];
            nibsRegistered = YES;
        }
        HomeCell *cell = (HomeCell *)[tableView dequeueReusableCellWithIdentifier:HomeTableCellIdentifiers];
        [cell loadDataWithProduct:[recommendations objectAtIndex:(indexPath.row-1)]];
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 194;
    } else return 173;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != 0) {
        ProductViewController *productVC = [[ProductViewController alloc] init];
        Product *corProduct = [recommendations objectAtIndex:(indexPath.row-1)];
        productVC.productID = corProduct.id;
        productVC.product = corProduct;
        [self.navigationController pushViewController:productVC animated:YES];
    }
}
#pragma tableView dataSource&delegate End

#pragma mark - bigWhiteLabelTapped
- (void)bigWhiteLabelTapped
{
    self.title = @"首页";
    UITabBarController *tabbar = (UITabBarController *)self.view.window.rootViewController;
    tabbar.selectedIndex = 2;
}
#pragma mark - bigWhiteLabelTapped End

#pragma mark - ScrollView Delegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.frame;
    [self.homeUpView.pageControl setCurrentPage:offset.x / bounds.size.width];
}
#pragma mark - ScrollView Delegate End

#pragma mark - PageControl Action
- (void)pageTurn:(UIPageControl*)sender
{
    CGSize viewSize = self.homeUpView.scrollView.frame.size;
    CGRect rect = CGRectMake(sender.currentPage * viewSize.width, 0, viewSize.width, viewSize.height);
    [self.homeUpView.scrollView scrollRectToVisible:rect animated:YES];
}
#pragma mark - PageControl Action End

@end
